<?php
namespace Admin\Model;
use Frame\Frame;
use Frame\Libs\BaseModel;

class ArticleModel extends BaseModel {
    private $table = 'articles';
    
    // 获取所有文章
    public function fetchAll() {
        $sql = "select * from $this->table order by id desc";
        $rows=$this->pdo->fetchAll($sql);
        if(!$rows) {
            return [];
        }
        else{
            return $rows;
        }
    }
    
    // 获取单篇文章
    public function fetchOne($id) {
        $id = intval($id);
        $sql = "select * from $this->table where id = :id";
        return $this->pdo->fetchOne($sql, array(':id' => $id));
    }
    
    // 添加文章
    public function insert($data) {
        $keys = array_keys($data);
        $values = array_values($data);
        
        $placeholders = array_map(function($key) { return ":$key"; }, $keys);
        
        $sql = "INSERT INTO $this->table (" . implode(', ', $keys) . ") VALUES (" . implode(', ', $placeholders) . ")";
        
        $params = array();
        foreach ($data as $key => $value) {
            $params[":$key"] = $value;
        }
        
        return $this->pdo->exec($sql, $params);
    }
    
    // 更新文章
    public function update($data, $id) {
        $id = intval($id);
        
        $setClause = array();
        $params = array(":id" => $id);
        
        foreach ($data as $key => $value) {
            $setClause[] = "$key = :$key";
            $params[":$key"] = $value;
        }
        
        $sql = "UPDATE $this->table SET " . implode(', ', $setClause) . " WHERE id = :id";
        
        return $this->pdo->exec($sql, $params);
    }
    
    // 删除文章
    public function delete($id) {
        $id = intval($id);
        $sql = "DELETE FROM $this->table WHERE id = :id";
        return $this->pdo->exec($sql, array(':id' => $id));
    }
    
    // 批量删除文章
    public function batchDelete($ids) {
        if(empty($ids) || !is_array($ids)) {
            return 0;
        }
        
        // 过滤并验证ID
        $validIds = array_filter($ids, function($id) { return is_numeric($id) && $id > 0; });
        
        if(empty($validIds)) {
            return 0;
        }
        
        // 构建IN子句
        $placeholders = array_map(function($key) { return ":id$key"; }, array_keys($validIds));
        $sql = "DELETE FROM $this->table WHERE id IN (" . implode(', ', $placeholders) . ")";
        
        // 构建参数数组
        $params = array();
        foreach ($validIds as $key => $id) {
            $params[":id$key"] = $id;
        }
        
        return $this->pdo->exec($sql, $params);
    }
    
    // 搜索文章
    public function search($keyword) {
        $keyword = $this->pdo->quote('%' . $keyword . '%');
        $sql = "SELECT * FROM $this->table WHERE title LIKE $keyword OR content LIKE $keyword OR author LIKE $keyword OR category LIKE $keyword ORDER BY id DESC";
        
        $rows = $this->pdo->fetchAll($sql);
        return $rows ? $rows : array();
    }
}